<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>发布新投票</title>
	<link type="text/css" rel="stylesheet" href="css/style.css" />
	<script type="text/javascript">
		var voteOptions = [];
		window.onload = function () {
			<c:forEach var="option" items="${voteSubject.voteOptions}" varStatus="status">
			<c:if test="${status.index >= 2}">
			voteOptions.push('<c:out value="${option.voOption}" />');
			</c:if>
			</c:forEach>
			for (var i = 0; i < voteOptions.length; i++) {
				AddOption(voteOptions[i]);
			}
			bindInputEvents();
			updateDeleteButtons();
			updateAddOptionButtonState();
		}
		function bindInputEvents() {
			var inputs = document.querySelectorAll("input[name='options']");
			inputs.forEach(function (input) {
				input.addEventListener('input', checkConditions);
			});
		}
		function AddOption(value) {
			if (hasDuplicateValues() || hasEmptyValues()) {
				updateAddOptionButtonState();
				return; // 禁止添加新选项
			}
			var voteOptionsContainer = document.getElementById("voteoptions");
			var p = document.createElement("p");

			// input for option value
			var input = document.createElement("input");
			input.type = "text";
			input.className = "input-text";
			input.name = "options";
			if (value) {
				input.value = value;
			}
			input.addEventListener('input', checkConditions);
			p.appendChild(input);

			// hidden input for vote id
			var voteIdInput = document.createElement("input");
			voteIdInput.type = "hidden";
			voteIdInput.name = "voId";
			voteIdInput.value = ""; // value should be set when fetching from backend, else default to empty
			p.appendChild(voteIdInput);

			voteOptionsContainer.appendChild(p);
			checkConditions();
			updateDeleteButtons(); // 为新添加的选项添加删除按钮
		}
		function DelOption(link) {
			var inputs = document.querySelectorAll("input[name='options']");
			if (inputs.length > 2) {
				var parentParagraph = link.parentNode;

				// 获取该选项对应的隐藏 ID
				var voteIdInput = parentParagraph.querySelector("input[name='voId']");
				if (voteIdInput) {
					var deletedIdsElement = document.getElementById("deletedIds");
					var deletedIds = deletedIdsElement.value;
					if (deletedIds) {
						deletedIdsElement.value = deletedIds + "," + voteIdInput.value;
					} else {
						deletedIdsElement.value = voteIdInput.value;
					}
				}

				parentParagraph.parentNode.removeChild(parentParagraph);
				checkConditions();
				updateDeleteButtons(); // 更新删除按钮状态
			}
		}
		function updateDeleteButtons() {
			var inputs = document.querySelectorAll("input[name='options']")
			var canDelete = inputs.length > 2;

			inputs.forEach(function (input) {
				var parent = input.parentNode;
				var deleteLink = parent.querySelector('.del');
				if ((inputs.length > 2) && !deleteLink) {
					var a = document.createElement("a");
					a.className = "del";
					a.href = "javascript:void(0);";
					a.onclick = function () {
						DelOption(a);
					};
					a.appendChild(document.createTextNode("删除"));
					parent.appendChild(a);
				} else if (deleteLink) {
					if (canDelete) {
						deleteLink.style.display = 'inline';
					} else {
						deleteLink.style.display = 'none';
					}
				}
			});
		}
		function checkConditions() {
			checkDuplicates();
			checkEmptyValues();
			updateAddOptionButtonState();
		}
		function checkDuplicates() {
			var inputs = document.querySelectorAll("input[name='options']");
			var values = {};
			var hasDuplicate = false;
			inputs.forEach(function (input) {
				if (input.value && input.value in values) {
					input.style.color = 'red';
					hasDuplicate = true;
				} else {
					input.style.color = '';
					values[input.value] = true;
				}
			});
			return hasDuplicate;
		}
		function checkEmptyValues() {
			var inputs = document.querySelectorAll("input[name='options']");
			var hasEmpty = false;
			inputs.forEach(function (input) {
				if (input.value.trim() === '') {
					hasEmpty = true;
				} else {
					input.style.border = '';
				}
			});
			return hasEmpty;
		}
		function hasDuplicateValues() {
			var inputs = document.querySelectorAll("input[name='options']");
			var values = {};
			for (var i = 0; i < inputs.length; i++) {
				if (inputs[i].value in values && inputs[i].value !== "") {
					return true;
				}
				values[inputs[i].value] = true;
			}
			return false;
		}
		function hasEmptyValues() {
			var inputs = document.querySelectorAll("input[name='options']");
			for (var i = 0; i < inputs.length; i++) {
				if (inputs[i].value.trim() === '') {
					return true;
				}
			}
			return false;
		}
		function updateAddOptionButtonState() {
			var addButton = document.getElementById('addOptionButton');
			if (hasDuplicateValues() || hasEmptyValues()) {
				addButton.style.color = 'red';
				addButton.disabled = true;
			} else {
				addButton.style.color = '';
				addButton.disabled = false;
			}
		}
		function validateForm() {
			var deletedIdsValue = document.getElementById("deletedIds").value;
			console.log('Deleted IDs to be submitted:', deletedIdsValue);
			return true;
		}
	</script>
</head>
<body>
<div id="voteManage" class="box">
	<h2>添加新投票</h2>
	<div class="content">
		<form id="voteForm" method="post" onsubmit="return validateForm()">
			<dl>
				<dt>投票内容：</dt>
				<dd>
					<input type="hidden" name="vsId" value="${voteSubject.vsId}" />
					<input type="text" class="input-text" name="vsTitle" value="${voteSubject.vsTitle}" />
				</dd>
				<dt>投票类型：</dt>
				<dd>
					<input type="radio" name="vsType" value="1" <c:if test="${voteSubject != null && voteSubject.vsType == 1}">checked="checked"</c:if> /> 单选
					<input type="radio" name="vsType" value="2" <c:if test="${voteSubject != null && voteSubject.vsType == 2}">checked="checked"</c:if> /> 多选
				</dd>
				<dt>投票选项：</dt>
				<dd id="voteoptions">
					<input type="hidden" id="deletedIds" name="deletedIds" value="" />
					<c:choose>
						<c:when test="${voteSubject == null}">
							<p><input type="text" class="input-text" name="options" /></p>
							<p><input type="text" class="input-text" name="options" /></p>
						</c:when>
						<c:otherwise>
							<c:if test="${fn:length(voteSubject.voteOptions) > 0}">
								<c:forEach items="${voteSubject.voteOptions}" var="option" varStatus="status">
									<c:if test="${status.index < 2}">
										<p>
											<input type="text" class="input-text" name="options" value="${option.voOption}" />
											<input type="hidden" name="voId" value="${option.voId}" />
										</p>
									</c:if>
								</c:forEach>
							</c:if>
						</c:otherwise>
					</c:choose>
				</dd>
				<dt></dt>
				<dd class="button">
					<input type="image" src="images/button_submit.gif" />
					<a id="addOptionButton" href="javascript:;" onclick="AddOption('')">增加选项</a>
					<a href="javascript:history.go(-1);">取消操作</a>
				</dd>
			</dl>
		</form>
	</div>
</div>
<div id="footer" class="wrap">
	北大青鸟 &copy; 版权所有
</div>
</body>
</html>